

export const Type = {
    NOTIFY: 0,
    SIMPLE_REQ: 1,
    SIMPLE_RES: 2,
    REQ: 3,
    RES: 4,
    PING: 5,
    PONG: 6,
}

export const Cmd = {
    LOG: 0,
    MOTOR_CTRL: 1,
    NUM_LED_CTRL: 2,
    DEBUG_IO: 3,
}

const respMap = new Map<number, (buf: number[]) => void>();

export function createRespPromise(type: number, seq: number, timeout: number, timeoutMsg: string) {
    const key = (type << 8) + seq;
    return new Promise<number[]>((resolve, reject) => {
        const timerId = setTimeout(() => {
            respMap.delete(key);
            reject(timeoutMsg);
        }, timeout);
        
        respMap.set(key, (item) => {
            clearTimeout(timerId);
            resolve(item);
        });
    });
}

export function onResp(type: number, seq: number, buf: number[]) {
    const key = (type << 8) + seq;
    const f = respMap.get(key);
    if (f == null) {
        return;
    }
    f(buf);
}


